package com.phiture.erp.sale.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialResp;
import com.phiture.erp.basic.api.service.ErpAccountApi;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.common.constants.ErpNoPrefixConstants;
import com.phiture.erp.common.enums.ErpAuditStatus;
import com.phiture.erp.common.enums.ErpStockRecordBizTypeEnum;
import com.phiture.erp.common.utils.ErpNoGenerator;
import com.phiture.erp.sale.core.pojo.dto.ErpSaleReturnPageReqDTO;
import com.phiture.erp.sale.core.pojo.dto.ErpSaleReturnSaveReqDTO;
import com.phiture.erp.sale.core.service.ErpSaleOrderService;
import com.phiture.erp.sale.core.service.ErpSaleReturnService;
import com.phiture.erp.sale.dal.entity.ErpSaleOrderDO;
import com.phiture.erp.sale.dal.entity.ErpSaleOutDO;
import com.phiture.erp.sale.dal.entity.ErpSaleReturnDO;
import com.phiture.erp.sale.dal.entity.ErpSaleReturnItemDO;
import com.phiture.erp.sale.dal.mapper.ErpSaleReturnItemMapper;
import com.phiture.erp.sale.dal.mapper.ErpSaleReturnMapper;
import com.phiture.erp.stock.api.pojo.req.ErpStockRecordCreateReq;
import com.phiture.erp.stock.api.service.ErpStockRecordApi;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static com.phiture.erp.common.constants.ErrorCodeConstants.*;

/**
 * @author YH
 * @date 2025/4/8
 */

@Service
@RequiredArgsConstructor
public class ErpSaleReturnServiceImpl implements ErpSaleReturnService {

    private final ErpSaleOrderService saleOrderService;
    private final ErpAccountApi erpAccountApi;
    private final AdminUserApi adminUserApi;
    private final ErpMaterialApi erpMaterialApi;
    private final ErpSaleReturnMapper saleReturnMapper;
    private final ErpNoGenerator erpNoGenerator;
    private final ErpSaleReturnItemMapper saleReturnItemMapper;
    private final ErpStockRecordApi stockRecordApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createSaleReturn(ErpSaleReturnSaveReqDTO createReqDTO) {
        // 1.1 校验销售订单已审核
        ErpSaleOrderDO saleOrder = saleOrderService.validateSaleOrder(createReqDTO.getOrderId());
        // 1.2 校验退货项的有效性
        List<ErpSaleReturnItemDO> saleReturnItems = validateSaleReturnItems(createReqDTO.getItems());
        // 1.3 校验结算账户
        erpAccountApi.validateAccount(createReqDTO.getAccountId());
        // 1.4 校验销售人员
        if (createReqDTO.getSaleUserId() != null) {
            adminUserApi.validateUser(createReqDTO.getSaleUserId());
        }
        // 1.5 生成退货单号，并校验唯一性
        String no = erpNoGenerator.generate(ErpNoPrefixConstants.SALE_RETURN_NO_PREFIX);
        validateSaleReturnNo(no);

        // 2.1 插入退货
        ErpSaleReturnDO saleReturn = BeanUtils.toBean(createReqDTO, ErpSaleReturnDO.class, in -> in
                        .setNo(no).setStatus(ErpAuditStatus.PROCESS.getStatus()))
                .setOrderNo(saleOrder.getNo()).setCustomerId(saleOrder.getCustomerId());
        calculateTotalPrice(saleReturn, saleReturnItems);
        saleReturnMapper.insert(saleReturn);
        // 2.2 插入退货项
        saleReturnItems.forEach(o -> o.setReturnId(saleReturn.getId()));
        saleReturnItemMapper.insertBatch(saleReturnItems);

        // 3. 更新销售订单的退货数量
        updateSaleOrderReturnCount(createReqDTO.getOrderId());
        return saleReturn.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSaleReturn(ErpSaleReturnSaveReqDTO updateReqVO) {
        // 1.1 校验存在
        ErpSaleReturnDO saleReturn = validateSaleReturnExists(updateReqVO.getId());
        if (ErpAuditStatus.APPROVE.getStatus().equals(saleReturn.getStatus())) {
            throw exception(SALE_RETURN_UPDATE_FAIL_APPROVE, saleReturn.getNo());
        }
        // 1.2 校验销售订单已审核
        ErpSaleOrderDO saleOrder = saleOrderService.validateSaleOrder(updateReqVO.getOrderId());
        // 1.3 校验结算账户
        erpAccountApi.validateAccount(updateReqVO.getAccountId());
        // 1.4 校验销售人员
        if (updateReqVO.getSaleUserId() != null) {
            adminUserApi.validateUser(updateReqVO.getSaleUserId());
        }
        // 1.5 校验订单项的有效性
        List<ErpSaleReturnItemDO> saleReturnItems = validateSaleReturnItems(updateReqVO.getItems());

        // 2.1 更新退货
        ErpSaleReturnDO updateObj = BeanUtils.toBean(updateReqVO, ErpSaleReturnDO.class)
                .setOrderNo(saleOrder.getNo()).setCustomerId(saleOrder.getCustomerId());
        calculateTotalPrice(updateObj, saleReturnItems);
        saleReturnMapper.updateById(updateObj);
        // 2.2 更新退货项
        updateSaleReturnItemList(updateReqVO.getId(), saleReturnItems);

        // 3.1 更新销售订单的出库数量
        updateSaleOrderReturnCount(updateObj.getOrderId());
        // 3.2 注意：如果销售订单编号变更了，需要更新“老”销售订单的出库数量
        if (ObjectUtil.notEqual(saleReturn.getOrderId(), updateObj.getOrderId())) {
            updateSaleOrderReturnCount(saleReturn.getOrderId());
        }
    }

    private void calculateTotalPrice(ErpSaleReturnDO saleReturn, List<ErpSaleReturnItemDO> saleReturnItems) {
        saleReturn.setTotalCount(getSumValue(saleReturnItems, ErpSaleReturnItemDO::getCount, BigDecimal::add));
        saleReturn.setTotalMaterialPrice(getSumValue(saleReturnItems, ErpSaleReturnItemDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO));
        saleReturn.setTotalTaxPrice(getSumValue(saleReturnItems, ErpSaleReturnItemDO::getTaxPrice, BigDecimal::add, BigDecimal.ZERO));
        saleReturn.setTotalPrice(saleReturn.getTotalMaterialPrice().add(saleReturn.getTotalTaxPrice()));
        // 计算优惠价格
        if (saleReturn.getDiscountPercent() == null) {
            saleReturn.setDiscountPercent(BigDecimal.ZERO);
        }
        saleReturn.setDiscountPrice(MoneyUtils.priceMultiplyPercent(saleReturn.getTotalPrice(), saleReturn.getDiscountPercent()));
        saleReturn.setTotalPrice(saleReturn.getTotalPrice().subtract(saleReturn.getDiscountPrice().add(saleReturn.getOtherPrice())));
    }

    private void updateSaleOrderReturnCount(Long orderId) {
        // 1.1 查询销售订单对应的销售出库单列表
        List<ErpSaleReturnDO> saleReturns = saleReturnMapper.selectListByOrderId(orderId);
        // 1.2 查询对应的销售订单项的退货数量
        Map<Long, BigDecimal> returnCountMap = saleReturnItemMapper.selectOrderItemCountSumMapByReturnIds(
                convertList(saleReturns, ErpSaleReturnDO::getId));
        // 2. 更新销售订单的出库数量
        saleOrderService.updateSaleOrderReturnCount(orderId, returnCountMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSaleReturnStatus(Long id, Integer status) {
        boolean approve = ErpAuditStatus.APPROVE.getStatus().equals(status);
        // 1.1 校验存在
        ErpSaleReturnDO saleReturn = validateSaleReturnExists(id);
        // 1.2 校验状态
        if (saleReturn.getStatus().equals(status)) {
            throw exception(approve ? SALE_RETURN_APPROVE_FAIL : SALE_RETURN_PROCESS_FAIL);
        }
        // 1.3 校验已退款
        if (!approve && saleReturn.getRefundPrice().compareTo(BigDecimal.ZERO) > 0) {
            throw exception(SALE_RETURN_PROCESS_FAIL_EXISTS_REFUND);
        }

        // 2. 更新状态
        int updateCount = saleReturnMapper.updateByIdAndStatus(id, saleReturn.getStatus(),
                new ErpSaleReturnDO().setStatus(status));
        if (updateCount == 0) {
            throw exception(approve ? SALE_RETURN_APPROVE_FAIL : SALE_RETURN_PROCESS_FAIL);
        }

        // 3. 变更库存
        List<ErpSaleReturnItemDO> saleReturnItems = saleReturnItemMapper.selectListByReturnId(id);
        Integer bizType = approve ? ErpStockRecordBizTypeEnum.SALE_RETURN.getType()
                : ErpStockRecordBizTypeEnum.SALE_RETURN_CANCEL.getType();
        saleReturnItems.forEach(saleReturnItem -> {
            BigDecimal count = approve ? saleReturnItem.getCount() : saleReturnItem.getCount().negate();
            stockRecordApi.createStockRecord(new ErpStockRecordCreateReq(
                    saleReturnItem.getMaterialId(), saleReturnItem.getWarehouseId(), count,
                    bizType, saleReturnItem.getReturnId(), saleReturnItem.getId(), saleReturn.getNo()));
        });
    }

    @Override
    public void updateSaleReturnRefundPrice(Long id, BigDecimal refundPrice) {
        ErpSaleReturnDO saleReturn = saleReturnMapper.selectById(id);
        if (saleReturn.getRefundPrice().equals(refundPrice)) {
            return;
        }
        if (refundPrice.compareTo(saleReturn.getTotalPrice()) > 0) {
            throw exception(SALE_RETURN_FAIL_REFUND_PRICE_EXCEED, refundPrice, saleReturn.getTotalPrice());
        }
        saleReturnMapper.updateById(new ErpSaleReturnDO().setId(id).setRefundPrice(refundPrice));
    }

    private List<ErpSaleReturnItemDO> validateSaleReturnItems(List<ErpSaleReturnSaveReqDTO.Item> list) {
        // 1. 校验物料存在
        List<ErpMaterialResp> materialList = erpMaterialApi.validMaterialList(
                convertSet(list, ErpSaleReturnSaveReqDTO.Item::getMaterialId));
        Map<Long, ErpMaterialResp> materialMap = convertMap(materialList, ErpMaterialResp::getId);
        // 2. 转化为 ErpSaleReturnItemDO 列表
        return convertList(list, o -> BeanUtils.toBean(o, ErpSaleReturnItemDO.class, item -> {
            item.setMaterialUnitId(materialMap.get(item.getMaterialId()).getUnitId());
            item.setTotalPrice(MoneyUtils.priceMultiply(item.getMaterialPrice(), item.getCount()));
            if (item.getTotalPrice() == null) {
                return;
            }
            if (item.getTaxPercent() != null) {
                item.setTaxPrice(MoneyUtils.priceMultiplyPercent(item.getTotalPrice(), item.getTaxPercent()));
            }
        }));
    }

    private void updateSaleReturnItemList(Long id, List<ErpSaleReturnItemDO> newList) {
        // 第一步，对比新老数据，获得添加、修改、删除的列表
        List<ErpSaleReturnItemDO> oldList = saleReturnItemMapper.selectListByReturnId(id);
        List<List<ErpSaleReturnItemDO>> diffList = diffList(oldList, newList, // id 不同，就认为是不同的记录
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));

        // 第二步，批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setReturnId(id));
            saleReturnItemMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            saleReturnItemMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            saleReturnItemMapper.deleteBatchIds(convertList(diffList.get(2), ErpSaleReturnItemDO::getId));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSaleReturn(List<Long> ids) {
        // 1. 校验不处于已审批
        List<ErpSaleReturnDO> saleReturns = saleReturnMapper.selectBatchIds(ids);
        if (CollUtil.isEmpty(saleReturns)) {
            return;
        }
        saleReturns.forEach(saleReturn -> {
            if (ErpAuditStatus.APPROVE.getStatus().equals(saleReturn.getStatus())) {
                throw exception(SALE_RETURN_DELETE_FAIL_APPROVE, saleReturn.getNo());
            }
        });

        // 2. 遍历删除，并记录操作日志
        saleReturns.forEach(saleReturn -> {
            // 2.1 删除订单
            saleReturnMapper.deleteById(saleReturn.getId());
            // 2.2 删除订单项
            saleReturnItemMapper.deleteByReturnId(saleReturn.getId());

            // 2.3 更新销售订单的出库数量
            updateSaleOrderReturnCount(saleReturn.getOrderId());
        });

    }

    private ErpSaleReturnDO validateSaleReturnExists(Long id) {
        ErpSaleReturnDO saleReturn = saleReturnMapper.selectById(id);
        if (saleReturn == null) {
            throw exception(SALE_RETURN_NOT_EXISTS);
        }
        return saleReturn;
    }

    @Override
    public ErpSaleReturnDO getSaleReturn(Long id) {
        return saleReturnMapper.selectById(id);
    }

    @Override
    public ErpSaleReturnDO validateSaleReturn(Long id) {
        ErpSaleReturnDO saleReturn = validateSaleReturnExists(id);
        if (ObjectUtil.notEqual(saleReturn.getStatus(), ErpAuditStatus.APPROVE.getStatus())) {
            throw exception(SALE_RETURN_NOT_APPROVE);
        }
        return saleReturn;
    }

    @Override
    public PageResult<ErpSaleReturnDO> getSaleReturnPage(ErpSaleReturnPageReqDTO pageReqDTO) {
        MPJLambdaWrapperX<ErpSaleReturnDO> query = new MPJLambdaWrapperX<ErpSaleReturnDO>()
                .likeIfPresent(ErpSaleReturnDO::getNo, pageReqDTO.getNo())
                .eqIfPresent(ErpSaleReturnDO::getCustomerId, pageReqDTO.getCustomerId())
                .betweenIfPresent(ErpSaleReturnDO::getReturnTime, pageReqDTO.getReturnTime())
                .eqIfPresent(ErpSaleReturnDO::getStatus, pageReqDTO.getStatus())
                .likeIfPresent(ErpSaleReturnDO::getRemark, pageReqDTO.getRemark())
                .eqIfPresent(ErpSaleReturnDO::getCreator, pageReqDTO.getCreator())
                .eqIfPresent(ErpSaleReturnDO::getAccountId, pageReqDTO.getAccountId())
                .likeIfPresent(ErpSaleReturnDO::getOrderNo, pageReqDTO.getOrderNo())
                .orderByDesc(ErpSaleReturnDO::getId);
        // 退款状态。为什么需要 t. 的原因，是因为联表查询时，需要指定表名，不然会报字段不存在的错误
        if (Objects.equals(pageReqDTO.getRefundStatus(), ErpSaleReturnPageReqDTO.REFUND_STATUS_NONE)) {
            query.eq(ErpSaleReturnDO::getRefundPrice, 0);
        } else if (Objects.equals(pageReqDTO.getRefundStatus(), ErpSaleReturnPageReqDTO.REFUND_STATUS_PART)) {
            query.gt(ErpSaleReturnDO::getRefundPrice, 0).apply("t.refund_price < t.total_price");
        } else if (Objects.equals(pageReqDTO.getRefundStatus(), ErpSaleReturnPageReqDTO.REFUND_STATUS_ALL)) {
            query.apply("t.refund_price = t.total_price");
        }
        if (Boolean.TRUE.equals(pageReqDTO.getRefundEnable())) {
            query.eq(ErpSaleOutDO::getStatus, ErpAuditStatus.APPROVE.getStatus())
                    .apply("t.refund_price < t.total_price");
        }
        if (pageReqDTO.getWarehouseId() != null || pageReqDTO.getProductId() != null) {
            query.leftJoin(ErpSaleReturnItemDO.class, ErpSaleReturnItemDO::getReturnId, ErpSaleReturnDO::getId)
                    .eq(pageReqDTO.getWarehouseId() != null, ErpSaleReturnItemDO::getWarehouseId, pageReqDTO.getWarehouseId())
                    .eq(pageReqDTO.getProductId() != null, ErpSaleReturnItemDO::getMaterialId, pageReqDTO.getProductId())
                    .groupBy(ErpSaleReturnDO::getId); // 避免 1 对多查询，产生相同的 1
        }
        return saleReturnMapper.selectJoinPage(pageReqDTO, ErpSaleReturnDO.class, query);
    }

    // ==================== 销售退货项 ====================

    @Override
    public List<ErpSaleReturnItemDO> getSaleReturnItemListByReturnId(Long returnId) {
        return saleReturnItemMapper.selectListByReturnId(returnId);
    }

    @Override
    public List<ErpSaleReturnItemDO> getSaleReturnItemListByReturnIds(Collection<Long> returnIds) {
        if (CollUtil.isEmpty(returnIds)) {
            return Collections.emptyList();
        }
        return saleReturnItemMapper.selectListByReturnIds(returnIds);
    }

    @Override
    public List<ErpSaleReturnDO> getSaleReturnList(Integer status, LocalDate startDate, LocalDate endDate) {
        List<ErpSaleReturnDO> list = saleReturnMapper.selectList(
                Wrappers.lambdaQuery(ErpSaleReturnDO.class)
                        .eq(ErpSaleReturnDO::getStatus, status)
                        .eq(ErpSaleReturnDO::getAccountCheckFlag, Boolean.FALSE)
                        .ge(startDate != null, ErpSaleReturnDO::getReturnTime, startDate)
                        .le(endDate != null, ErpSaleReturnDO::getReturnTime, endDate)
        );
        return CollUtil.isEmpty(list) ? Collections.emptyList() : list;
    }

    @Override
    public void backfillSaleReturnAccountCheckFlag(Collection<Long> saleReturnIds, Boolean accountCheckFlag) {
        if(CollUtil.isEmpty(saleReturnIds)){
            return;
        }

        List<ErpSaleReturnDO> list = saleReturnIds.stream().map(saleReturnId -> {
            ErpSaleReturnDO saleReturnDO = new ErpSaleReturnDO();
            saleReturnDO.setId(saleReturnId);
            saleReturnDO.setAccountCheckFlag(accountCheckFlag);
            return saleReturnDO;
        }).collect(Collectors.toList());
        saleReturnMapper.updateBatch(list);
    }

    @Override
    public void updateSaleReturnAccountCheckFlag(Collection<String> saleReturnNos, Boolean accountCheckFlag) {
        if(CollUtil.isEmpty(saleReturnNos)){
            return;
        }

        saleReturnMapper.update(
                Wrappers.lambdaUpdate(ErpSaleReturnDO.class)
                        .set(ErpSaleReturnDO::getAccountCheckFlag, accountCheckFlag)
                        .in(ErpSaleReturnDO::getNo, saleReturnNos)
        );
    }

    private void validateSaleReturnNo(String no) {
        boolean exists = saleReturnMapper.exists(
                Wrappers.lambdaQuery(ErpSaleReturnDO.class)
                        .eq(ErpSaleReturnDO::getNo, no)
                        .eq(ErpSaleReturnDO::getDeleted, Boolean.FALSE)
        );
        if (exists) {
            throw exception(SALE_RETURN_NO_EXISTS);
        }
    }
}
